<script setup lang="ts">
import { EditArticleDataAPI, getArticleDetailAPI, publishAPI, UpLoadImageAPI } from '@/api/article'
import GeekChannels from '@/compontents/Geek-Channels.vue'
import router from '@/router'
import type { PublishArticleRes } from '@/types/Public'
import { ArrowRight, Plus } from '@element-plus/icons-vue'
import {
  ElMessage,
  type FormInstance,
  type UploadFile,
  type UploadRequestOptions,
  type UploadUserFile,
} from 'element-plus'
import { ref } from 'vue'
import { useRoute } from 'vue-router'

const PushArticleParams = ref<PublishArticleRes>({
  title: '', //文章标题
  content: '', //文章内容
  cover: {
    type: 1, //封面类型
    images: [], //封面图片数组
  },
  channel_id: '', //频道id
})

const imageRules = (
  _: object,
  value: PublishArticleRes['cover'],
  callback: (error?: Error) => void,
) => {
  if (value.type === 1 && value.images.length < 1) {
    return callback(new Error('请上传一张图片'))
  } else if (value.type === 3 && value.images.length < 3) {
    return callback(new Error('请上传三张图片'))
  } else {
    return callback()
  }
}

const PushArticleFormRules = ref({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  channel_id: [{ required: true, message: '请选择频道', trigger: 'blur' }],
  cover: [{ validator: imageRules, trigger: 'change' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
})

// 图片上传
const fileList = ref<UploadUserFile[]>([])
const PushArticleFormRef = ref<FormInstance>()
// 上传图片
const UpLoadImages = async (options: UploadRequestOptions) => {
  const fd = new FormData()
  fd.append('image', options.file)
  const res = await UpLoadImageAPI(fd)
  // console.log(res)
  PushArticleParams.value.cover.images.push(res.data.url)
  PushArticleFormRef.value?.validateField('cover')
  return res.data.url
}

// 删除图片
const onRemove = (File: UploadFile) => {
  // console.log(uploadFile)
  PushArticleParams.value.cover.images = PushArticleParams.value.cover.images.filter(
    (item) => item !== File.response,
  )
  PushArticleFormRef.value?.validateField('cover')
}

const route = useRoute()
// 数据回显
const getArticleDetail = async () => {
  const res = await getArticleDetailAPI(route.params.id as string)
  // console.log(res)
  const { channel_id, content, cover, title } = res.data
  PushArticleParams.value = {
    title,
    content,
    cover,
    channel_id,
  }
  // 回显图片
  fileList.value = cover.images.map((item: string) => {
    return {
      url: item,
      name: item,
      Response: item,
    }
  })
}

if (route.params.id) {
  getArticleDetail()
}

// 修改文章
const EditArticle = async (draft: boolean) => {
  await EditArticleDataAPI(PushArticleParams.value, route.params.id as string, draft)
  ElMessage.success(draft ? '保存草稿成功' : '修改文章成功')
  router.back()
}

// 发布文章
const onsubmit = async (draft: boolean) => {
  PushArticleFormRef.value?.validate(async (res) => {
    if (res) {
      try {
        await publishAPI(PushArticleParams.value, draft)
        ElMessage.success(draft ? '保存草稿成功' : '发布文章成功')
        router.push('/article')
      } catch {}
    }
  })
}

// 富文本失去焦点
const checkContent = () => {
  PushArticleFormRef.value?.validateField('content')
}
</script>

<template>
  <el-card>
    <template #header>
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>

        <!-- 通过template编组,通过一个v-if控制对个标签的条件渲染 -->
        <template v-if="$route.params.id">
          <el-breadcrumb-item :to="{ path: '/article' }">内容管理</el-breadcrumb-item>
          <el-breadcrumb-item>修改文章</el-breadcrumb-item>
        </template>

        <el-breadcrumb-item v-else>发布文章</el-breadcrumb-item>
      </el-breadcrumb>
    </template>
    <!-- 表单数据 -->
    <el-form
      label-width="120px"
      :model="PushArticleParams"
      :rules="PushArticleFormRules"
      ref="PushArticleFormRef"
    >
      <el-form-item label="标题：" style="width: 450px" prop="title">
        <el-input placeholder="请输入标题" v-model="PushArticleParams.title"></el-input>
      </el-form-item>

      <el-form-item label="频道：" prop="channel_id" style="width: 450px">
        <GeekChannels v-model="PushArticleParams.channel_id" />
      </el-form-item>

      <el-form-item label="封面：" prop="cover">
        <el-radio-group v-model="PushArticleParams.cover.type">
          <el-radio :value="1">单图</el-radio>
          <el-radio :value="3">三图</el-radio>
          <el-radio :value="0">无图</el-radio>
          <el-radio :value="-1">自动</el-radio>
        </el-radio-group>

        <!-- 插入图片 -->
        <div v-if="PushArticleParams.cover.type === 1 || PushArticleParams.cover.type === 3">
          <el-upload
            ref="upload"
            action=""
            list-type="picture-card"
            :http-request="UpLoadImages"
            :on-remove="onRemove"
            v-model:file-list="fileList"
            :limit="PushArticleParams.cover.type"
            preview-teleported="true"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </div>
      </el-form-item>

      <!-- 内容 -->
      <el-form-item label="内容：" prop="content">
        <QuillEditor
          theme="snow"
          content-type="html"
          ref="quillEditor"
          v-model:content="PushArticleParams.content"
          @blur="checkContent()"
        ></QuillEditor>
      </el-form-item>

      <el-form-item v-if="$route.params.id">
        <el-button type="primary" @click="EditArticle(false)">修改文章</el-button>
        <el-button @click="EditArticle(true)">存入草稿</el-button>
      </el-form-item>

      <el-form-item v-else>
        <el-button type="primary" @click="onsubmit(false)">发布文章</el-button>
        <el-button @click="onsubmit(true)">存入草稿</el-button>
      </el-form-item>
    </el-form>
    {{ PushArticleParams }}
  </el-card>
</template>

<style scoped>
/* 样式 */
::v-deep .el-form-item__content {
  display: block;
}
.el-button {
  margin-top: 50px;
}
::v-deep .ql-editor {
  min-height: 220px;
}
</style>
